package com.wang.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.common.utils.PageUtils;
import com.wang.common.utils.Query;

import com.wang.gulimall.product.dao.CategoryDao;
import com.wang.gulimall.product.entity.CategoryEntity;
import com.wang.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //返回树形结构数据需要两个步骤：1、查询出所有数据；2、将所有数据以树形结构封装起来
        //baseMapper是包含泛型CategoryEntity，查询出来的结果便是它的集合

        //查询出所有的菜单
        List<CategoryEntity> entities = baseMapper.selectList(null);

        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
            //找出这个菜单的子菜单
        }).map((menu)->{
            //找到并设置这个菜单的子菜单。getChildrenMenus(menu,entities)是返回菜单menu的子菜单，然后通过setChildren函数进行设置子菜单集合
            menu.setChildren(getChildrenMenus(menu,entities));
            return menu;
            //对菜单进行排序
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
            //将菜单转换成集合返回
        }).collect(Collectors.toList());
        return level1Menus;
    }

    public List<CategoryEntity> getChildrenMenus(CategoryEntity root,List<CategoryEntity> all) {
        //过滤找到root的子菜单
        List<CategoryEntity> childrenMenus = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
            //同样，子菜单也可能有自己的子菜单，所以需要递归.map的作用便是让元素以另一种形式输出。
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrenMenus(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return childrenMenus;
    }
}